import React, { useState, useEffect } from "react";
import Tabpane from "./tabpane.jsx";
import {
  Card,
  Form,
  Input,
  Button,
  Space,
  Table,
  Layout,
  Select,
  Col,
  Row,
  Tabs,
  Modal,
  Radio,
  Popconfirm, Typography
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { auths } from "../../api/auth/data.js";
import { getAuthList, editAuth, addAuth } from "../../api/auth/index";
export const GlobalContext = React.createContext();
const styles = { marginTop: "20px", width: "100%", textAlign: "center" };

const { Content } = Layout;
const { Option } = Select;
const { TabPane } = Tabs;
const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `输入 ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};
function NewService1() {
  const [form] = Form.useForm();
  const [formEdit] = Form.useForm();
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: "32%",
    },
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (text, _) => {
        return +text === 0 ? "停止" : "启用";
      },
      filters: [
        {
          text: "启用",
          value: "1",
        },
        {
          text: "停止",
          value: "0",
        },
      ],
      onFilter: (value, record) => {
        return String(record.status) === String(value);
      },
      width: "20%",
    },
    {
      title: "Action",
      key: "action",
      render: (text, record) => (
        // console.log(text, record),
        <Space size="middle">
          <a onClick={() => onEdit(record)}>编辑</a>
          <a onClick={() => remove(record)}>删除</a>
        </Space>
      ),
    },
  ];
  const columnsEdit = [
    {
      title: '操作类型',
      dataIndex: 'action',
      width: '25%',
      editable: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: '15%',
      editable: true,
    },
    {
      title: '描述',
      dataIndex: 'describe',
      width: '40%',
      editable: true,
    },
    {
      title: <div>操作 | {<PlusOutlined />}</div>,
      dataIndex: "operate",
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.action)}
              style={{
                marginRight: 8,
              }}
            >
              保存
            </Typography.Link>
            <Popconfirm title="确定取消？" onConfirm={cancel} okText="确定" cancelText="取消">
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <div>
            <Typography.Link disabled={editingaction !== ''} onClick={() => newedit(record)}>
              编辑
            </Typography.Link>
            <span> | </span>
            <Typography.Link disabled={editingaction !== ''} onClick={() => onClickDelete(record)}>
              删除
            </Typography.Link>
          </div>
        );
      },
    },
  ];
  const [data, setData] = useState([])

  const [editingaction, setEditingaction] = useState('');

  const isEditing = (record) => record.action === editingaction;

  const newedit = (record) => {
    formEdit.setFieldsValue({
      action: '',
      name: '',
      describe: '',
      ...record,
    });
    setEditingaction(record.action);
  };

  const cancel = () => {
    setEditingaction('');
  };
  const save = async (action) => {
    try {
      const row = await formEdit.validateFields();
      const newData = [...permissionStorage.actions];
      const index = newData.findIndex((item) => action === item.action);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setPermissionStorage({id: permissionStorage.id,
          name: permissionStorage.name,
          status: permissionStorage.status,
          actions: newData,})
        setData(newData);
        setEditingaction('');
      } else {
        newData.push(row);
        setData(newData);
        
        setEditingaction('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
  const mergedColumns = columnsEdit.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  //权限列表
  const [newAuths, setNewAuths] = useState([]);
  useEffect(() => {
    setNewAuths([...getAuthList()]);
  }, [getAuthList().length, edit]);

  const onFinish = (values) => {
    let newlist = getAuthList().filter(
      (item) =>
        (values.id && item.id.toUpperCase().includes(values.id.toUpperCase())) ||
        (values.name && item.name.toUpperCase().includes(values.name.toUpperCase()))
    );
    setNewAuths(newlist);
  };
  const onReset = () => {
    form.resetFields();
    setNewAuths([...getAuthList()]);
  };
  // 页数变化
  // function onChange(pagination, filters, sorter, extra) {
  //   console.log("params", pagination, filters, sorter, extra);
  // }
  //新增模块
  const [isModalVisible, setIsModalVisible] = useState(false);
  const showModal = () => {
    setIsModalVisible(!isModalVisible);
  };
  //删除权限
  const remove = (record) => {
    let auths = newAuths.filter((e) => e.id !== record.id);
    setNewAuths([...auths]);
  };
  //编辑
  const [edit, setEdit] = useState(false);
  const [permissionStorage, setPermissionStorage] = useState([]);
  const onEdit = (record) => {
    formEdit.resetFields();
    
    setPermissionStorage(record);
    setData(record.actions)
    setEdit(true);
  };
  const handleCancel = () => {
    setEdit(false);
    setPermissionStorage([]);
  };

  //编辑删除权限
  const onClickDelete = (record) => {
    let newdata = permissionStorage.actions.filter(
      (e) => e.action !== record.action
    );
    setPermissionStorage({
      id: permissionStorage.id,
      name: permissionStorage.name,
      status: permissionStorage.status,
      actions: newdata,
    });
  };
  const handleOk = (e) => {
  if(e.getFieldsValue().purviewID||e.getFieldsValue().purviewName){
    let newauth = {
      id: e.getFieldsValue().purviewID,
      name: e.getFieldsValue().purviewName,
      status: e.getFieldsValue().condition ? 1 : 0,
      actions: data,
    };
    setNewAuths(editAuth(permissionStorage.id, newauth));
    
  }
  setEdit(false); 
  };
  //新增-标签页
  return (
    <GlobalContext.Provider value={{ isModalVisible, setIsModalVisible }}>
      <Card>
        <Row>
          <Form
            layout="inline"
            form={form}
            name="control-hooks"
            onFinish={onFinish}
            style={{ width: "100%" }}
          >
            <Col span={8}>
              <Form.Item name="id" label="ID">
                <Input placeholder="请输入ID" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="name" label="名称">
                <Input placeholder="请输入名称" />
              </Form.Item>
            </Col>

            <Col
              span={8}
              style={{ display: "flex", justifyContent: "flex-end" }}
            >
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button htmlType="button" onClick={onReset}>
                  重置
                </Button>
              </Form.Item>
            </Col>
          </Form>
        </Row>
        <div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            style={{ marginTop: "40px" }}
            onClick={showModal}
          >
            新增
          </Button>
          <Tabpane />
        </div>
        <Content style={{ margin: "15px 0" }}>
          {/* {console.log(newAuths)} */}
          <Table
            columns={columns}
            dataSource={newAuths}
            // onChange={onChange}
            rowKey="id"
          />
        </Content>
        <Modal
          title="新建权限"
          visible={edit}
          onOk={() => handleOk(formEdit)}
          onCancel={handleCancel}
          okText="确定"
          cancelText="取消"
          width={1000}
        >
          <div>
            <Tabs defaultActiveKey="1">
              <TabPane tab="基本信息" key="1">
                <div>
                  <Row>
                    <Form
                      form={formEdit}
                      layout="inline"
                      requiredMark={true}
                      // onValuesChange={()=>onChangeForm(form)}
                      style={styles}
                    >
                      <Col span={9} offset={3}>
                        <Form.Item
                          label="权限标识(ID):"
                          style={styles}
                          name="purviewID"
                          rules={[
                            {
                              required: true,
                              message: "请输入权限标识符",
                            },
                          ]}
                        >
                          <Input defaultValue={permissionStorage.id} />
                        </Form.Item>
                      </Col>
                      <Col span={9}>
                        <Form.Item
                          label="权限名称:"
                          style={styles}
                          name="purviewName"
                          rules={[
                            {
                              required: true,
                              message: "请输入权限标名称",
                            },
                          ]}
                        >
                          <Input defaultValue={permissionStorage.name} />
                        </Form.Item>
                      </Col>
                      <Col span={9} offset={3}>
                        <Form.Item
                          label="状态:"
                          style={styles}
                          name="condition"
                          rules={[
                            {
                              required: true,
                              message: "请选择状态",
                            },
                          ]}
                        >
                          <Radio.Group
                            buttonStyle="solid"
                            defaultValue={permissionStorage.status !== 0}
                          >
                            <Radio.Button value={true}>启用</Radio.Button>
                            <Radio.Button value={false}>禁用</Radio.Button>
                          </Radio.Group>
                        </Form.Item>
                      </Col>
                      <Col span={24}>
                        {/* <Table
                          name="permission"
                          columns={columnsEdit}
                          dataSource={permissionStorage.actions}
                          pagination={false}
                          style={styles}
                          rowKey="name"
                          title={() => "操作配置"}
                        /> */}
                        <Table
                          components={{
                            body: {
                              cell: EditableCell,
                            },
                          }}
                          bordered
                          dataSource={permissionStorage.actions}
                          columns={mergedColumns}
                          rowClassName="editable-row"
                          pagination={{
                            onChange: cancel,
                          }}
                        />
                      </Col>
                    </Form>
                  </Row>
                </div>
              </TabPane>
            </Tabs>
          </div>
        </Modal>
      </Card>
    </GlobalContext.Provider>
  );
}

export default NewService1;
